import React, { useEffect, useState } from 'react';
import '@/views/Index/Column/Column.scss'
import { useNavigate } from "react-router-dom";
import Nav from '../../../components/Nav/Nav'
import service from '../../../api/index'
import { Table, Form, Radio, Input, Select, Button, Col, Row, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';




interface Props {

}

interface DataType {
    key: React.Key;
    id: string;
    news: any;
    price: string;
    count: string;
    state: string;
    starttime: string;
    order: string;
    courses: string;
}

function Column(props: Props) {

    let navigator = useNavigate()

    // 发请求
    useEffect(() => {
        columnlist({ page: 1, limit: 5 })
    }, [])

    let columnlist = async (payload = {}) => {
        let res = await service.dy.column_list(payload)
        console.log(res);
        // 给数据添加key属性
        res.data.map((item: any) => {
            item.key = item.id
        })
        setDateSource(res.data)
        setTotal(res.data.length)
    }

    const { Option } = Select;

    const [form] = Form.useForm();

    // 表格数据源
    let [dataSource, setDateSource] = useState<DataType[]>([])

    // 总数量
    let [total, setTotal] = useState()

    // 查询
    let onFinish = async (values: any) => {
        console.log(values);
        if (values.state == 'all') {
            let res = await service.dy.column_list()
            setDateSource(res.data)
            setTotal(res.data.length)
        } else {
            let res = await service.dy.column_search(values)
            setDateSource(res.data)
            setTotal(res.data.length)
        }

    }

    // 重置
    const onReset = () => {
        form.resetFields();
    };

    // 表头
    const columns: ColumnsType<DataType> = [
        // {
        //     title: '序号', //表格列的标题
        //     dataIndex: 'id', //数据索引( 属性名 )
        //     // key: 'order',
        //     // width: '6%',
        //     align: 'center',
        // },
        {
            title: '专栏信息',
            dataIndex: 'news',
            align: 'center',
            width: '20%',
            render: (_, record) => {
                return <div className='news'>
                    <img src={record.news.pic} alt="" />
                    <a className='name' href="#">{record.news.name}</a>
                </div>
            }
        },
        {
            title: '专栏价格(元)',
            dataIndex: 'price',
            align: 'center',
        },
        {
            title: '订阅量',
            dataIndex: 'count',
            align: 'center',
        },
        {
            title: '专栏状态',
            dataIndex: 'state',
            align: 'center',
            render: (_, record) => record.state == '1' ? '已上架' : (record.state == '0' ? '已下架' : '待上架')
        },
        {
            title: '上架时间',
            dataIndex: 'ontime',
            align: 'center',
            width: '12%',
        },
        {
            title: '排序号',
            dataIndex: 'order',
            align: 'center',
        },
        {
            title: '包含课程数量',
            dataIndex: 'courses',
            align: 'center',
        },
        {
            title: '操作',
            align: 'center',
            width: '20%',
            render: (_, record) => {
                return <>
                    <a className='data option_btn' onClick={() => { navigator('') }}>
                        数据
                    </a>
                    <a className='edit option_btn' onClick={toColumnEdit}>
                        编辑
                    </a>
                    <a className='off option_btn' onClick={() => { columnState(record) }}>
                        {record.state == '0' || record.state == '2' ? '上架' : '下架'}
                    </a>
                    <a className='delete option_btn' onClick={() => {
                        columnDelete(record.id)
                    }}>
                        删除
                    </a>
                </>
            }
        },

    ];

    // 跳转到编辑页面
    let toColumnEdit = () => {
        navigator('/index/column_edit')
    }

    // 更改数据状态(上架/下架)
    let columnState = async ({ state, id }: { state: any, id: any }) => {
        if (state == 1) {
            let res = await service.dy.column_update({ id: id, state: 0 })
            columnlist({ page: 1, limit: 5 })
        } else if (state == 2) {
            let res = await service.dy.column_update({ id: id, state: 1 })
            columnlist({ page: 1, limit: 5 })
        } else {
            message.success({ content: '商品已下架' })
        }
    }

    // 删除一条数据
    let columnDelete = async (id: any) => {
        let res = await service.dy.column_delete({ id: id })
        columnlist({ page: 1, limit: 5 })
    }

    //   新建
    let toColumnAdd = () => {
        navigator('/column_add')
    }

    // 批量管理
    let batchAll = () => { }

    // 分页设置
    let pageChange = (page: any, pageSize: any) => {
        // console.log(page, pageSize);
        columnlist({ page: page, limit: pageSize })
    };

    // 复选框(全选/选择)
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState(false);

    const start = () => {
        setLoading(true);
        // ajax request after empty completing
        setTimeout(() => {
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    };

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;


    return (
        <div className='column'>
            <Nav />
            <div className="query">
                <Form
                    className='form'
                    form={form}
                    name="control-hooks"
                    onFinish={onFinish}
                >
                    <Row>
                        <Col span={1}></Col>
                        <Col span={6}>
                            <Form.Item name="state" label="课程状态" rules={[{ required: false }]}>
                                <Select
                                    placeholder="请选择课程状态"
                                    allowClear
                                >
                                    <Option value="all">全部</Option>
                                    <Option value="2">待上架</Option>
                                    <Option value="1">已上架</Option>
                                    <Option value="0">已下架</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={4}></Col>
                        <Col span={6}>
                            <Form.Item name="name" label="课程名称" rules={[{ required: false }]}>
                                <Input placeholder='请输入' />
                            </Form.Item>
                        </Col>
                        <Col span={7}></Col>
                    </Row>

                    <Row>
                        <Col span={1}></Col>
                        <Col span={8}>
                            <Form.Item name="starttime" label="上架日期" rules={[{ required: false }]}>
                                <Select
                                    placeholder="开始日期~结束日期"
                                    allowClear
                                >
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={1}></Col>
                        <Col span={6}>
                            <Form.Item name="time" label="" rules={[{ required: false }]}>
                                <Radio.Group size="small">
                                    <Radio.Button value="1">今日</Radio.Button>
                                    <Radio.Button value="2">昨日</Radio.Button>
                                    <Radio.Button value="7">最近7天</Radio.Button>
                                    <Radio.Button value="30">最近30天</Radio.Button>
                                </Radio.Group>
                            </Form.Item>

                        </Col>
                        <Col span={4}></Col>
                        <Col span={3}>
                            <Form.Item>
                                <Button className='search' type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button className='reset' htmlType="button"
                                    onClick={onReset}
                                >
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div className="list">
                <div className="top">
                    <div className="title">
                        课程列表
                    </div>
                    <div className="btn">
                        <Button className='add' type="primary" icon={<PlusOutlined />} onClick={toColumnAdd}>
                            新建
                        </Button>
                        <Button className='batch' onClick={start} disabled={!hasSelected} loading={loading}>
                            批量管理
                        </Button>
                    </div>
                </div>
                <Table className='table' rowSelection={rowSelection} dataSource={dataSource} columns={columns} scroll={{ y: 420 }} pagination={{
                    showSizeChanger: false,
                    onChange: pageChange,
                    defaultCurrent: 1,
                    total: total
                }} />
            </div>
        </div>
    );
}

export default Column;